package com.qingcloud.fexecutor.service;

import cn.hutool.core.util.StrUtil;
import com.qingcloud.fexecutor.base.enums.DataSourceEnum;
import com.qingcloud.fexecutor.base.utils.AesUtil;
import com.qingcloud.fexecutor.mapper.AppDataSourceMapper;
import com.qingcloud.fexecutor.model.AppDataSource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Collections;

/**
 * Docker基础镜像service.
 */
@Service
public class AppDataSourceService {

    @Resource
    private AppDataSourceMapper appDataSourceMapper;

    /**
     * 使用数据源
     */
    public AppDataSource findUseInfo(Integer dsId) {
        AppDataSource appDataSource = appDataSourceMapper.selectByPrimaryKey(dsId);
        appDataSource.setJdbcUrl(buildJdbcUrl(appDataSource));
        appDataSource.setPassword(AesUtil.decryptHex(appDataSource.getPassword(), StandardCharsets.ISO_8859_1));
        return appDataSource;
    }

    /**
     * 使用数据源
     */
    public AppDataSource findUseInfo(Integer appId, String code) {
        AppDataSource appDataSource = appDataSourceMapper.findByCode(appId, Collections.singletonList(code)).get(0);
        appDataSource.setJdbcUrl(buildJdbcUrl(appDataSource));
        appDataSource.setPassword(AesUtil.decryptHex(appDataSource.getPassword(), StandardCharsets.ISO_8859_1));
        return appDataSource;
    }

    /**
     * 不同数据库类型生成jdbc url
     */
    private String buildJdbcUrl(AppDataSource appDataSource) {
        if (DataSourceEnum.MYSQL.code.equals(appDataSource.getType())) {
            return StrUtil.format("jdbc:mysql://{}:{}/{}?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false",
                    appDataSource.getIp(), appDataSource.getPort(), appDataSource.getCatalog());
        }
        if (DataSourceEnum.PGSQL.code.equals(appDataSource.getType())) {
            return StrUtil.format("jdbc:postgresql://{}:{}/{}",
                    appDataSource.getIp(), appDataSource.getPort(), appDataSource.getCatalog());
        }
        if (DataSourceEnum.ORACLE.code.equals(appDataSource.getType())) {
            return StrUtil.format("jdbc:oracle:thin:@{}:{}:{}",
                    appDataSource.getIp(), appDataSource.getPort(), appDataSource.getCatalog());
        }
        if (DataSourceEnum.SQLSERVER.code.equals(appDataSource.getType())) {
            return StrUtil.format("jdbc:microsoft:sqlserver//{}:{}; DatabaseName={}",
                    appDataSource.getIp(), appDataSource.getPort(), appDataSource.getCatalog());
        }
        return "";
    }

}
